<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;
use think\Db;

class Casus extends Common
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //
        $casus = db('casus')->paginate(10);
        $this->assign('casus', $casus);
        return view();
    }

    // 添加/编辑案例
    public function save_casus() {
        $id = input('param.id');
        if (Request::instance()->isPost()) {
            // 提交数据
            $data = [
                'name' => input('param.name'),
                'add_time' => time()
            ];

            $post_image = input('param.image', '');
            if ($post_image) {
                // 如果图片有值  则获取旧图并删除
                $image = db('casus')->where('id', $id)->value('image');
                if ($image) {
                    unlink('./uploads/nav/'.$image);
                }
                $data['image'] = $post_image;
            }

            if ($id > 0)  {
                $text = '编辑';
                $rs = db('casus')->where('id', $id)->update($data);
                $url = url('index');
                db('casus_content')->where('casus_id', $id)->update(['content'=> input('param.content', ''), 'info' => input('param.info', '')]);
            } else {
                $text = '添加';
                $rs = db('casus')->insertGetId($data);
                $url = url('save_casus', 'id=' . $rs);
                db('casus_content')->insert(['content'=> input('param.content', ''), 'casus_id' => $rs]);
            }
            if ($rs)
                return json(['code' => 200, 'msg' => $text . '案例成功！', 'url' => $url]);
            else
                return json(['code' => 0, 'msg' => $text . '案例失败！']);
        } else {
            if ($id > 0) {
                $casus = db('casus')->alias('c')->field('c.*, cc.content, cc.info')
                    ->join('osl_casus_content cc', 'c.id = cc.casus_id', 'LEFT')->where('c.id', $id)->find();
                $this->assign('casus', $casus);
            }
            
            return view();
        }
    }
}
